﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using asMeishi.web.Models;
using publicLibrary;


namespace asMeishi.web.Controllers
{
    using Classes;
    public class sitePublicController : Controller
    {
        //
        // GET: /sitePublic/

        public ActionResult getTopShop(int num = 10)
        {

            shopC sc = new shopC();
            ViewData.Model = sc.getAll(true).OrderByDescending(d=>d.lasttime).Take(num).ToList();

            return View();

        }
        /// <summary>
        /// 最新更新的推荐菜肴
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public ActionResult getTopFood(int num = 20)
        {

            foodC fc = new foodC();
            ViewData.Model = fc.db.query.OrderByDescending(d => d.lastDatatime).Take(num).ToList();

            return View();

        }
        public ActionResult getTopShop2(int num = 5)
        {

            shopC sc = new shopC();
            ViewData.Model = sc.getAll(true).OrderByDescending(d => d.lasttime).Take(num).ToList();

            return View();
        }
        public ActionResult getHotShop(int num = 10)
        {

            shopC sc = new shopC();
            ViewData.Model = sc.getAll(true).OrderByDescending(d => d.comment_number).Take(num).ToList();

            return View();
        }
        /// <summary>
        /// 最热的菜肴recommend
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public ActionResult getHotFood(int num = 10)
        {

            foodC fc = new foodC();
            ViewData.Model = fc.db.query.OrderByDescending(d => d.recommendCount).Take(num).ToList();

            return View();

        }

        public ActionResult getSumShop(int num = 5)
        {

            shopC sc = new shopC();
            ViewData.Model = sc.getAll(true).OrderByDescending(d => d.sum_score).Take(num).ToList();

            return View();


        }
        public ActionResult getTopComment(int num=5)
        {
            commentC cc = new commentC();
            ViewData.Model = cc.getTopByDate().Take(num).ToList();

            return View();
        }

        public ActionResult getTopImpressByFood(int num = 5)
        {
            impressionC<food> ic = new impressionC<food>();
            var _userdb = userC.getDB().query;
            var _fooddb = new foodC().db.query;

            var impress = ic.getAll().OrderByDescending(d => d.datetime).Take(num).ToList();

            var result = (from c in impress //第一个表
                          join u in _userdb //第二个表
                          on c.userId equals u.Id //条件
                          into uDef //默认值处理
                          join f in _fooddb on c.targetId equals f.Id into fDef from fD in fDef.DefaultIfEmpty(new food())
                          from uD in uDef.DefaultIfEmpty(userC.guestUser)
        
                          select new Object[] { c, uD,fD}).ToList(); //返回

            ViewData.Model = result;
            return View();
        }
        public ActionResult getTopImpressByShop(int num = 5)
        {
            impressionC<shop> ic = new impressionC<shop>();
            ViewData.Model = ic.getAll().OrderByDescending(d => d.datetime).Take(num).ToList();
            return View();
        }

        public ActionResult toolTipKeyWord(string keyword)
        {
            keyWordC kwc = new keyWordC();
            var _toolTipKW = kwc.getToolTip(keyword);

            var re = _toolTipKW.Select(d => new { d.value /*,d.Id*/}).Take(6).ToList();

            return Json(re, JsonRequestBehavior.AllowGet);
            
        }

        /// <summary>
        /// 得到相类似的店
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult AlikeShop(shop shop)
        {
            shopC sc = new shopC();
            //sc.getAll().Join(

            return View();
        }
        public ActionResult getRandomRecommendShop(int id = 5)
        {
            /*
             后期完成推荐条件
            */

            var dbss = new shopC().db.query.Where(d => d.picUrlList != null && d.picUrlList.Count() != 0);

            Random r = new Random();
            //用来保存随机生成的不重复的id个数
            int RandomNum = id;
            int site = dbss.Count();//设置下限

            //如果小于=1个。放弃
            if (site <= 1)
            {
                return View(dbss);
            }

            if (site < RandomNum)
            {
                RandomNum = site;
            }
            int[] result = functionExt.GetRandomUnrepeatArray(0,site-1, RandomNum);
            
            shop[] ss = new shop[RandomNum];


            for (int ii = 0; ii < RandomNum; ii++)
            {

                ss[ii] = dbss.ElementAt(result[ii]);

            }
            //var _s = ss.Select(d => new { d.name, sum_score = d.sum_score.ToString("0.0"), Id = d.Id.ToString(), d.foodStyle, d.size, address = d.city + " " + d.area + " " + d.street, d.sales, pic = d.picUrlList != null ? d.picUrlList.FirstOrDefault() : null });

            ViewData.Model = ss;
            return View();
        }


        public ActionResult getRandomRecommendFood(int id = 5)
        {
            /*
             后期完成推荐条件
            */
            var dbff = new foodC().db.query.Where(d => d.picUrls != null && d.picUrls.Count() != 0);

            Random r = new Random();
            //用来保存随机生成的不重复的id个数
            int RandomNum = id;
            
            int site = dbff.Count();

            if (site < RandomNum)
            {
                RandomNum = site;
            }
            //如果小于=1个。放弃
            if (site <= 1)
            {
                return View(dbff);
            }
            int[] result = functionExt.GetRandomUnrepeatArray(0,site-1, RandomNum);

            food[] ff = new food[RandomNum];

            for (int ii = 0; ii < RandomNum; ii++)
            {

                ff[ii] = dbff.ElementAt(result[ii]);

            }

            ViewData.Model = ff;
            return View();
        }
        public JsonResult Ajax_getRandomShop(int id = 6) {



            Random r = new Random();
            //用来保存随机生成的不重复的10个数
            int RandomNum = id;
            int site = int.Parse(publicDictApp.shopTotalCount.ToString());//设置下限
            if (site < RandomNum)
            {
                RandomNum = site ;
            }
            int[] result = new int[RandomNum];

            int j = 0;
            int _p = 0;//计算次数
            while (j<RandomNum && _p<1000)
            {
                var _n = r.Next(1, site - 1);
                if(!result.Contains(_n)){
                    result[j] = _n;
                    j++;
                }
                _p++;
                
            }
            shopC sc = new shopC();
            shop[] ss = new shop[RandomNum];

            for (int ii = 0; ii < RandomNum; ii++)
            {

                ss[ii] = sc.db.query.ElementAt(result[ii]);

            }
            var _s = ss.Select(d => new { d.name,sum_score= d.sum_score.ToString("0.0"), Id=d.Id.ToString(), d.foodStyle,d.size,address=d.city + " "+d.area +" "+d.street,d.sales,pic=d.picUrlList!=null?d.picUrlList.FirstOrDefault():null  });

            return Json(_s, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 店的排行榜（代码块）
        /// </summary>
        /// <param name="id">排序字段</param>
        /// <param name="p1">排序方式，仅为asc是为正序</param>
        /// <returns></returns>
        public ActionResult shopRanking(string id, string p1)
        {
            IndexOrder IndexOrder = (p1 ?? "").ToLower() == "asc" ? IndexOrder.Ascending : IndexOrder.Descending;
            var sort = new Dictionary<string, IndexOrder>();
            sort.Add(id, IndexOrder);
            ViewData.Model = new rankingClass(sort).content;
            return View();
        }

        public ActionResult shopRank()
        {
            Dictionary<string, object> info = new Dictionary<string, object>();
            info["总分排行"] = new { field = "total_score", IndexOrder = IndexOrder.Descending};
            info["质量排行"] = new { field = "quality", IndexOrder = IndexOrder.Descending };
            info["服务排行"] = new { field = "service", IndexOrder = IndexOrder.Descending };
            info["环境排行"] = new { field = "priceQuality", IndexOrder = IndexOrder.Descending };
            info["性价排行"] = new { field = "cost", IndexOrder = IndexOrder.Descending };
            info["最新"] = new { field = "createtime", IndexOrder = IndexOrder.Descending };
            info["最新修改"] = new { field = "lasttime", IndexOrder = IndexOrder.Descending };

            ViewData.Model = info;

            return View();
        }

        class rankingClass
        {
            public int limit = 10;
            public Dictionary<string, IndexOrder> sort = new Dictionary<string, IndexOrder>();

            public rankingClass(Dictionary<string, IndexOrder> sort = null)
            {
                if (sort != null) this.sort = sort;
            }

            public List<shop> content
            {
                get
                {
                    var db = new DataSession<MongoDataContext, shop>();

                    var temp = db.Mquery.FindAll();
                        if (sort != null)
                            foreach (var item in sort)
                            {
                                var xx = typeof(shop).GetField(item.Key);

                                if (item.Value == IndexOrder.Ascending)
                                {
                                    temp.OrderBy(d => xx);
                                }
                                else
                                {
                                    temp.OrderByDescending(d => xx);
                                }

                            }
                        temp = temp.SetLimit(limit);
                        return temp.ToList();

                }
            }
        }

    }
}